package cn.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import cn.pojo.Bill;
import cn.pojo.Role;
import cn.pojo.Unit;
import cn.pojo.User;
import cn.service.BillService;
import cn.service.BillServiceImpl;
import cn.service.RoleService;
import cn.service.RoleServiceImpl;
import cn.service.UnitService;
import cn.service.UnitServiceImpl;
import cn.service.UserService;
import cn.service.UserServiceImp;
import cn.util.Commons;
import cn.util.DateUtil;
import cn.util.EncodeUtil;
import cn.util.ExcelUtil;
import cn.util.FileDownload;
import cn.util.PackObject;
import cn.util.Page;

/**
 * Servlet implementation class MainController
 */
@WebServlet("*.html")
public class MainController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger(MainController.class);
	private UserService userService = new UserServiceImp();
	private RoleService roleService = new RoleServiceImpl();
	private BillService billService = new BillServiceImpl();
	private UnitService unitService = new UnitServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		// 获得servlet的请求路径
		String path = request.getServletPath();
		System.out.println("before=" + path);
		path = path.substring(1, path.indexOf("."));
		System.out.println("after=" + path);
		try {
			Class<?> cl = Class.forName("cn.controller.MainController");
			Method mt = cl.getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
			mt.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
			request.getSession().setAttribute("ERROR", "此方法不存在");
			response.sendRedirect("jsp/login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 1、登录
	public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 对象绑定
		User u = PackObject.getObject(request, User.class);
		// 加密
		u.setUserPassword(EncodeUtil.enconding(u.getUserPassword()));
		// 执行登录
		u = userService.login(u);
		System.out.println(u);
		HttpSession session = request.getSession();
		if (u != null) {
			session.setAttribute("USER_LOGIN", u);
			request.getRequestDispatcher("/WEB-INF/pages/welcome.jsp").forward(request, response);
		} else {
			session.setAttribute("ERROR", "错误的用户名或密码！");
			response.sendRedirect("jsp/login.jsp");
		}
	}

	// 2、退出
	public void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getSession().invalidate();
		response.sendRedirect("jsp/login.jsp");
	}

	// 3、用户管理
	public void userList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		// 2、获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<User> page = new Page<User>();
		// 4、根据userName获得总条数
		int sum = userService.totalCount(userName);
		page.init(sum, pageNum);
		// 5、根据用户名进行模糊分页查询
		List<User> list = userService.getUserLike(userName, page.getRowNum(), Page.pageCount);
		for (User user : list) {
			user.setRole(roleService.getRoleById(user.getUserRole()));
		}
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("USERNAME", userName);
		// 7、到userList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/userList.jsp").forward(request, response);
	}

	// 4、批量删除
	public void deleteBatch(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String id[] = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Integer[] num = userService.deleteBatch(id);
		System.out.println("删除了" + num[0] + "条");
		HttpSession session = request.getSession();
		session.setAttribute("DELETENUM", num[0]);
		response.sendRedirect("userList.html");
	}

	// 5单个删除
	public void userRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		int i = userService.userRemove(id);
		response.sendRedirect("userList.html");
	}

	// 6导出excel表格
	public void exportExcel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String[] id = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		List<User> list = userService.getUserByid(id);
		// 调用POI
		// request.getServletContext()===appilcation
		String path = request.getServletContext().getRealPath("excel");
		String fileName = Commons.getFileName("user.xlsx");
		path += File.separator + fileName;// path=D:/tomcat8/java53smsm/excel/sduuyeruser.xlsx
		ExcelUtil.generateExcel(list, path);
		// 执行下载操作
		FileDownload.download(request, response, fileName, path);
	}

	// 7到用户添加界面
	public void toUserAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/userAdd.jsp").forward(request, response);
	}

	// 获得所有角色信息返回给客户端：json
	public void getAllRoles(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(request.getParameter("name"));
		response.setContentType("text/html;charset=utf-8");
		List<Role> list = roleService.getAllRoles();
		PrintWriter out = response.getWriter();
		String msg = JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd HH:mm:ss",
				SerializerFeature.WriteDateUseDateFormat);
		System.out.println(msg);
		out.write(msg);
		out.flush();
		out.close();
	}

	public void ajaxUserList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		// 2、获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<User> page = new Page<User>();
		// 4、根据userName获得总条数
		int sum = userService.totalCount(userName);
		page.init(sum, pageNum);
		// 5、根据用户名进行模糊分页查询
		List<User> list = userService.getUserLike(userName, page.getRowNum(), Page.pageCount);
		for (User user : list) {
			user.setRole(roleService.getRoleById(user.getUserRole()));
		}
		page.setList(list);
		// 保存变量的map
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("PAGE", page);
		map.put("USERNAEM", userName);
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONStringWithDateFormat(map, "yyyy-MM-dd HH:mm:ss",
				SerializerFeature.WriteDateUseDateFormat);
		out.write(json);
		out.flush();
		out.close();
	}

	// testUserCode:根用户编码获得用户
	public void testUserCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String userCode = request.getParameter("userCode");
		userCode = userCode == null ? "" : userCode;
		User user = userService.getUserByUserCode(userCode);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (user != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void testUserName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		User user = userService.getUserByUserName(userName);
		System.out.println(userName);
		System.out.println(user);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (user != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	public void testPhone(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String phone = request.getParameter("phone");
		phone = phone == null ? "" : phone;
		User user = userService.getUserByPhone(phone);
		System.out.println(phone);
		System.out.println(user);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (user != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	// userAdd：用户添加注册
	public void userAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		System.out.println(request.getParameter("userName"));
		// 1、获得FileItemFactory
		FileItemFactory factory = new DiskFileItemFactory();
		// 2、 获得文件上传的请求解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 3、判断是否是文件上传
		Boolean flag = ServletFileUpload.isMultipartContent(request);
		// 创建对象，保存提交的参数值
		User user = new User();
		if (!flag) {
			// 不是多文件上传，反回添加页面
			response.sendRedirect("toUserAdd.html");
			return;
		}
		List<FileItem> list = new ArrayList<FileItem>();
		try {
			// 4、是多文件上传，解析request对象
			list = upload.parseRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 5、遍历集合处理FileItem对象，封装成User对象
		for (int i = 0; i < list.size(); i++) {
			FileItem item = list.get(i);// userName=tom&age=20&gender=1
			// 6、分解item，判断item的类型A、form文本域 B、form的文件域
			// 判断是否是form文本域
			boolean isField = item.isFormField();
			if (isField) {
				// 7、文本域的处理过程
				String fieldName = item.getFieldName();// userName
				String value = item.getString("UTF-8");// tom
				if (fieldName.equalsIgnoreCase("userName")) {
					user.setUserName(value);
				} else if (fieldName.equalsIgnoreCase("userCode")) {
					user.setUserCode(value);
				} else if (fieldName.equalsIgnoreCase("userPassword")) {
					user.setUserPassword(value);
				} else if (fieldName.equalsIgnoreCase("gender")) {
					int v = 1;
					try {
						v = Integer.parseInt(value);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					user.setGender(v);
				} else if (fieldName.equalsIgnoreCase("birthday")) {
					user.setBirthday(DateUtil.convertStringToTimestamp(value));
				} else if (fieldName.equalsIgnoreCase("phone")) {
					user.setPhone(value);
				} else if (fieldName.equalsIgnoreCase("address")) {
					user.setAddress(value);
				} else if (fieldName.equalsIgnoreCase("userRole")) {
					int v = 1;
					try {
						v = Integer.parseInt(value);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					user.setUserRole(v);
				}
			} else {
				// 8、文件域的处理过程
				// 9、获得文件名称
				String fileName = item.getName();// tom123.jpg
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				// 如果不是图片
				if (!Commons.isPicture(suffix)) {
					// 回到添加页面
					response.sendRedirect("toUserAdd.html");
					return;
				}
				// 10、获得文件的大小
				long size = item.getSize();// 字节
				// 11、判断文件是否符合要求
				if (!Commons.isSiutSize(size)) {
					// 回到添加页面
					response.sendRedirect("toUserAdd.html");
				}
				// 12、修改文件的名称
				fileName = Commons.getFileName(fileName);
				// 13、指定上传文件的路径：文件夹在服务器的外部，需要手动创建
				String path = "E:/java53fileUpload/" + fileName;
				// 14、配置虚拟路径:在tomcat中要进行配置server.xml
				String virtualPath = "/fileUpload/" + fileName;
				user.setPicpath(virtualPath);
				// 15、执行上传操作
				try {
					item.write(new File(path));
				} catch (Exception e) {
					e.printStackTrace();
				}
			} // end of else
		} // end of for
			// 16、执行user对象的添加操作
		int i = userService.addUser(user);
		System.out.println("添加" + i + "条成功");
		// 17、添加结束后到登录界面测试能否登录
		response.sendRedirect("jsp/login.jsp");
	}

	// 查看用户信息
	public void userView(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		User user = userService.getUsersById(id);
		// System.out.println("USERVIEW>>>>>>>>>>>>>>>>>>>" + user);
		user.setRole(roleService.getRoleById(user.getUserRole()));
		request.setAttribute("USERVIEW", user);
		request.getRequestDispatcher("/WEB-INF/pages/userView.jsp").forward(request, response);
	}

	/**
	 * 账单管理----------------------------------------------------------------------------------
	 */
	// 去账单管理页面
	public void billList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1、获得页面提交的用户名
		String productName = request.getParameter("productName");
		productName = productName == null ? "" : productName;
		// 2.获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3.构建page对象封装信息
		Page<Bill> page = new Page<Bill>();

		// 4. 更具userName获得总条数
		int sum = billService.totalCount(productName);
		page.init(sum, pageNum);
		// 5.根据用户名进行模糊分页查询
		List<Bill> list = billService.getBillLike(productName, page.getRowNum(), Page.pageCount);
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("PRODUCTNAME", productName);
		// 7、到userList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/billList.jsp").forward(request, response);
	}

	// 批量删除
	public void deleteBill(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String id[] = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Integer[] num = billService.deleteBill(id);
		HttpSession session = request.getSession();
		session.setAttribute("DELETENUM", num[0]);
		response.sendRedirect("billList.html");

	}

	// 单个删除
	public void billRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		int num = billService.billRemove(id);
		response.sendRedirect("billList.html");
	}

	// 导出Excel
	public void billExportExcel(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String[] id = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		List<Bill> list = billService.getBillsByIdArray(id);
		// 条用POI
		// getServletContext()===application
		String path = request.getServletContext().getRealPath("excel");
		String fileName = Commons.getFileName("bill.xlsx");
		path += File.separator + fileName;// path=D:/tomcat8/java53smsm/excel/sduuyeruser.xlsx
		ExcelUtil.generateBillExcel(list, path);
		// 执行下载操作
		FileDownload.download(request, response, fileName, path);
	}

	// 查看用户
	public void billView(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("id");
		Integer id = 0;
		try {
			id = Integer.parseInt(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bill bill = billService.getBillById(id);
		request.setAttribute("BILL", bill);
		request.getRequestDispatcher("/WEB-INF/pages/billView.jsp").forward(request, response);

	}

	// 到修改页面
	public void toBillUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("id");
		Integer id = 0;
		try {
			id = Integer.parseInt(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bill bill = billService.getBillById(id);
		Date date = DateUtil.convertTimeStampToUtilDate(bill.getCreationDate());
		System.out.println(date);
		// bill.setCreationDate(DateUtil.convertTimeStampToUtilDate(bill.getCreationDate()));
		request.setAttribute("DATE", date);
		request.setAttribute("BILL", bill);
		request.getRequestDispatcher("/WEB-INF/pages/billUpdate.jsp").forward(request, response);
	}

	// 修改数据
	public void doBillUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg1 = request.getParameter("id");
		System.out.println(msg1);
		// String billCode = request.getParameter("billCode");
		String productName = request.getParameter("productName");
		String productDesc = request.getParameter("productDesc");
		String productUnit = request.getParameter("productUnit");
		String msg3 = request.getParameter("productCount");
		String msg4 = request.getParameter("totalPrice");
		String msg5 = request.getParameter("isPayment");
		String msg6 = request.getParameter("createdBy");
		String creationDate = request.getParameter("creationDate");
		String msg7 = request.getParameter("providerId");
		Long id = (long) 0;
		Double productCount = 0.0;
		Double totalPrice = 0.0;
		Integer isPayment = 0;
		Long createdBy = (long) 0;
		Integer providerId = 0;
		try {
			id = (long) Integer.parseInt(msg1);
			productCount = Double.parseDouble(msg3);
			totalPrice = Double.parseDouble(msg4);
			isPayment = Integer.parseInt(msg5);
			createdBy = (long) Integer.parseInt(msg6);
			providerId = Integer.parseInt(msg7);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bill bill = new Bill();
		bill.setId(id);
		// bill.setBillCode(billCode);
		bill.setCreatedBy(createdBy);
		bill.setCreationDate(
				cn.util.DateUtil.convertUtilDateToTimeStamp(cn.util.DateUtil.convertStringToUtilDate(creationDate)));
		bill.setIsPayment(isPayment);
		bill.setProductCount(productCount);
		bill.setProductDesc(productDesc);
		bill.setProductName(productName);
		bill.setProductUnit(productUnit);
		bill.setProviderId(providerId);
		bill.setTotalPrice(totalPrice);
		int i = billService.updateBillById(bill);
		response.sendRedirect("billList.html");

	}

	// 去添加界面
	public void toAddBill(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/addBill.jsp").forward(request, response);
	}

	// testBillCode根据用户名获得用户
	public void testBillCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String billCode = request.getParameter("billCode");
		billCode = billCode == null ? "" : billCode;
		Bill bill = billService.getBillByBillCode(billCode);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (bill != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	// 添加账单
	public void doAddBill(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String billCode = request.getParameter("billCode");
		String productName = request.getParameter("productName");
		String productDesc = request.getParameter("productDesc");
		String productUnit = request.getParameter("productUnit");
		String msg3 = request.getParameter("productCount");
		String msg4 = request.getParameter("totalPrice");
		String msg5 = request.getParameter("isPayment");
		String msg6 = request.getParameter("createdBy");
		String msg7 = request.getParameter("providerId");
		Double productCount = 0.0;
		Double totalPrice = 0.0;
		Integer isPayment = 0;
		Long createdBy = (long) 0;
		Integer providerId = 0;
		try {
			productCount = Double.parseDouble(msg3);
			totalPrice = Double.parseDouble(msg4);
			isPayment = Integer.parseInt(msg5);
			createdBy = (long) Integer.parseInt(msg6);
			providerId = Integer.parseInt(msg7);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Bill bill = new Bill();
		bill.setBillCode(billCode);
		bill.setCreatedBy(createdBy);
		bill.setIsPayment(isPayment);
		bill.setProductCount(productCount);
		bill.setProductDesc(productDesc);
		bill.setProductName(productName);
		bill.setProductUnit(productUnit);
		bill.setProviderId(providerId);
		bill.setTotalPrice(totalPrice);
		int i = billService.addBill(bill);
		response.sendRedirect("billList.html");
	}

	// 获得所有单位信息返回给客户端：json
	public void getAllUnit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		List<Unit> list = unitService.getAllUnit();
		PrintWriter out = response.getWriter();
		String msg = JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd HH:mm:ss",
				SerializerFeature.WriteDateUseDateFormat);
		out.write(msg);
		out.flush();
		out.close();
	}

	// 用户的修改
	public void userUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		User user = userService.getUsersById(id);
		user.setRole(roleService.getRoleById(user.getUserRole()));
		request.setAttribute("USERUPDATE", user);
		request.getRequestDispatcher("/WEB-INF/pages/userUpdate.jsp").forward(request, response);
	}

	// doUserUpdate
	public void doUserUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// System.out.println(request.getParameter("userName"));
		// 1、获得FileItemFactory
		FileItemFactory factory = new DiskFileItemFactory();
		// 2、 获得文件上传的请求解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 3、判断是否是文件上传
		Boolean flag = ServletFileUpload.isMultipartContent(request);
		// 创建对象，保存提交的参数值
		User user = new User();
		if (!flag) {
			// 不是多文件上传，反回添加页面
			response.sendRedirect("toUserAdd.html");
			return;
		}
		List<FileItem> list = new ArrayList<FileItem>();
		try {
			// 4、是多文件上传，解析request对象
			list = upload.parseRequest(request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 5、遍历集合处理FileItem对象，封装成User对象
		for (int i = 0; i < list.size(); i++) {
			FileItem item = list.get(i);// userName=tom&age=20&gender=1
			// 6、分解item，判断item的类型A、form文本域 B、form的文件域
			// 判断是否是form文本域
			boolean isField = item.isFormField();
			if (isField) {
				// 7、文本域的处理过程
				String fieldName = item.getFieldName();// userName
				String value = item.getString("UTF-8");// tom
				if (fieldName.equalsIgnoreCase("userName")) {
					user.setUserName(value);
				} else if (fieldName.equalsIgnoreCase("userCode")) {
					user.setUserCode(value);
				} else if (fieldName.equalsIgnoreCase("userPassword")) {
					user.setUserPassword(value);
				} else if (fieldName.equalsIgnoreCase("gender")) {
					int v = 1;
					try {
						v = Integer.parseInt(value);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					user.setGender(v);
				} else if (fieldName.equalsIgnoreCase("birthday")) {
					user.setBirthday(DateUtil.convertStringToTimestamp(value));
				} else if (fieldName.equalsIgnoreCase("phone")) {
					user.setPhone(value);
				} else if (fieldName.equalsIgnoreCase("address")) {
					user.setAddress(value);
				} else if (fieldName.equalsIgnoreCase("userRole")) {
					int v = 1;
					try {
						v = Integer.parseInt(value);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					user.setUserRole(v);
				} else if (fieldName.equalsIgnoreCase("id")) {
					long v = 0L;
					try {
						v = Long.parseLong(value);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					}
					user.setId(v);
				}
			} else {
				// 8、文件域的处理过程
				// 9、获得文件名称
				String fileName = item.getName();// tom123.jpg
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				// 如果不是图片
				if (!Commons.isPicture(suffix)) {
					// 回到添加页面
					response.sendRedirect("toUserAdd.html");
					return;
				}
				// 10、获得文件的大小
				long size = item.getSize();// 字节
				// 11、判断文件是否符合要求
				if (!Commons.isSiutSize(size)) {
					// 回到添加页面
					response.sendRedirect("toUserAdd.html");
					return;
				}
				// 12、修改文件的名称
				fileName = Commons.getFileName(fileName);
				// 13、指定上传文件的路径：文件夹在服务器的外部，需要手动创建
				String path = "E:/java53fileUpload/" + fileName;
				// 14、配置虚拟路径:在tomcat中要进行配置server.xml
				String virtualPath = "/fileUpload/" + fileName;
				user.setPicpath(virtualPath);
				// 15、执行上传操作
				try {
					item.write(new File(path));
				} catch (Exception e) {
					e.printStackTrace();
				}
			} // end of else
		} // end of for
			// 16、执行user对象的添加操作
		int i = userService.updateUser(user);
		System.out.println(user);
		System.out.println("修改" + i + "条成功");
		// 17、添加结束后到登录界面测试能否登录
		response.sendRedirect("userList.html");
	}

	public void roleAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String roleCode = request.getParameter("roleCode");
		String roleName = request.getParameter("roleName");
		String createdBy1 = request.getParameter("roleCreatedBy");
		System.out.println(createdBy1);
		Long createdBy = (long) 0;
		createdBy = (long) Integer.parseInt(createdBy1);
		Timestamp date = DateUtil.convertUtilDateToTimeStamp(new Date());
		Role role = new Role();
		role.setRoleCode(roleCode);
		role.setRoleName(roleName);
		role.setCreatedBy(createdBy);
		role.setCreationDate(date);
		int i = roleService.addRole(role);
		response.sendRedirect("roleList.html");
	}

	// roleList
	public void roleList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("1");
		// 1、获得页面提交的用户名
		String roleName = request.getParameter("roleName");
		roleName = roleName == null ? "" : roleName;
		// 2、获得页码
		String msg = request.getParameter("pageNum");
		Integer pageNum = 1;
		try {
			pageNum = Integer.parseInt(msg);
		} catch (NumberFormatException e) {
			log.debug(e.getMessage());// 捕捉异常
		}
		// 3、构建page对象封装信息
		Page<Role> page = new Page<Role>();
		// 4、根据roleName获得总条数
		int sum = roleService.totalCount(roleName);
		page.init(sum, pageNum);
		// 5、根据roleName进行模糊分页查询
		List<Role> list = roleService.getRoleLike(roleName, page.getRowNum(), Page.pageCount);
		/*
		 * for (Role role : list) { role.setRole(roleService.getroleName(); }
		 */
		page.setList(list);
		// 6、保存数据到Model中
		request.setAttribute("PAGE", page);
		request.setAttribute("ROLENAME", roleName);
		// 7、到roleList.jsp页面去，展示信息
		request.getRequestDispatcher("/WEB-INF/pages/roleList.jsp").forward(request, response);
	}

	// toRoleAdd
	public void toRoleAdd(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/roleAdd.jsp").forward(request, response);
	}

	// testRoleCode:根据用户角色编码获得用户
	public void testRoleCode(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String roleCode = request.getParameter("roleCode");
		roleCode = roleCode == null ? "" : roleCode;
		Role role = roleService.getRoleByRoleCode(roleCode);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (role != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	// testRoleName:根据用户角色名称获得用户角色
	public void testRoleName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String roleName = request.getParameter("roleName");
		roleName = roleName == null ? "" : roleName;
		Role role = roleService.getRoleByRoleName(roleName);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (role != null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	// 去修改密码页面
	public void password(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/pages/password.jsp").forward(request, response);
	}

	// testUserPsss根据用户名获得用户
	public void testUserPsss(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String pass = request.getParameter("pass");
		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		pass = pass == null ? "" : pass;
		String passWord = EncodeUtil.enconding(pass);
		User user = userService.getUserByUP(userName, passWord);
		System.out.println(user + "----" + userName + "----" + passWord);
		Map<String, Boolean> map = new HashMap<String, Boolean>();
		// 被占用了，返回false
		if (user == null) {
			map.put("result", false);
		} else {
			map.put("result", true);
		}
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String json = JSON.toJSONString(map);
		out.write(json);
		out.flush();
		out.close();
	}

	// 验证两次输入的密码是否一致
	public void doPassWord(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String pass = request.getParameter("pass");
		String pass1 = request.getParameter("pass1");
		String userName = request.getParameter("userName");
		userName = userName == null ? "" : userName;
		pass = pass == null ? "" : pass;
		pass1 = pass1 == null ? "" : pass1;
		String passWord = EncodeUtil.enconding(pass);
		String passWord1 = EncodeUtil.enconding(pass1);
		int i = userService.UpdatePassWord(userName, passWord, passWord1);
		if (i > 0) {
			response.sendRedirect("jsp/login.jsp");
		} else {
			request.getRequestDispatcher("/WEB-INF/pages/password.jsp").forward(request, response);
		}
	}

	// roleRemove 单个删除用户角色
	public void roleRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String id = request.getParameter("id");
		int num = roleService.roleRemove(id);
		response.sendRedirect("roleList.html");
	}

	// deleteAll 批量删除
	public void deleteAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String msg = request.getParameter("arr");
		String id[] = {};
		try {
			id = msg.split(",");
		} catch (Exception e) {
			log.debug(e.getMessage());
		}
		Integer[] num = roleService.deleteAll(id);
		System.out.println("删除了" + num[0] + "条");
		HttpSession session = request.getSession();
		session.setAttribute("DELETENUM", num[0]);
		response.sendRedirect("roleList.html");
	}
}
